export interface Modal {
    id: string
}


export class PageInfo {
    pageSize: number;
    pageIndex: number;

    constructor(pageIndex: number = 1, pageSize: number = 10) {
        this.pageIndex = pageIndex;
        this.pageSize = pageSize;
    }

    setPageIndex(pageIndex: number) {
        this.pageIndex = pageIndex;
    }

    setPageSize(pageSize: number) {
        this.pageSize = pageSize;
    }

    getStart() {
        return this.pageSize * (this.pageIndex - 1);
    }
    getEnd() {
        return this.pageSize * (this.pageIndex);
    }
}

export class PageData {
    total: number = 0;
    items: Modal[] = new Array<Modal>();;
    constructor(total: number) {
        this.total = total;
    }
    addItem(item: Modal) {
        this.items.push(item);
    }
}

export default class LocalStore<T extends Modal>{
    storeName: string;
    list: T[] = new Array<T>();
    constructor(storeName: string) {
        this.storeName = storeName;
        this.load();
    }
    load() {
        let s: string = localStorage.getItem(this.storeName);
        if (s) {
            this.list = JSON.parse(s) as Array<T>;
        } else {
            this.list = new Array<T>();
        }
    }

    flush() {
        localStorage.setItem(this.storeName, JSON.stringify(this.list));
    }

    get(id: string) {
        let i = this.findIndex(id);
        if (i >= 0) {
            return this.list[i];
        } else {
            return null;
        }
    }

    save(data: T) {
        let i = this.findIndex(data);
        if (i == -1) {
            this.list.unshift(data);
        } else {
            this.list[i] = data;
        }
        this.flush();
    }

    remove(id: string) {
        let i = this.findIndex(id);
        if (i >= 0) {
            this.list.splice(i, 1);
            this.flush();
        }
    }

    copy() {
        let item: T = Object.assign({}, this.list[0]);
        item.id = parseInt(item.id) + 1 + '';
        this.save(item);
    }

    getPage(page: PageInfo): PageData {
        const start = page.getStart();
        const end = page.getEnd();
        const total = this.list.length;
        const max = Math.min(end, total);
        
        const pageData: PageData = new PageData(total);
        for (let i = start; i < max; i++) {
            pageData.addItem(this.list[i]);
        }

        return pageData;
    }


    findIndex(data: T | string): number {
        let id = typeof data === 'string' ? data : data.id;
        let i = -1;
        this.list.map((item: T, index: number, arr: T[]) => {
            if (item.id == id) {
                i = index;
                return false;
            }
        });
        return i;
    }

}
